﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace AdslMonitorLibrary
{
    public class AdslSnrReader: IDisposable
    {
        private string _address;
        WebClientExtended _webclient;

        const string SNRKEY = "var downNM = '";

        public AdslSnrReader(string address, string userName, string password)
        {
            _address = address;
            _webclient = new WebClientExtended();
            _webclient.Timeout = 500;
            _webclient.Credentials = new NetworkCredential(userName, password);
        }

        /// <summary>
        /// Query the modem for the current SNR in dB
        /// </summary>
        /// <returns>Rturns the dB as string. If return value is -1 then it is not connected.</returns>
        public string ReadSnr()
        {
            string response = _webclient.DownloadString(_address);
            //Search for "var downNM = " and return the SNR in dB

            int posKey = response.IndexOf(SNRKEY);
            if (posKey < 0)
                return "0";

            int posComma = response.IndexOf("';", posKey);
            int dBLength = posComma - posKey - SNRKEY.Length;
            return response.Substring(posKey + SNRKEY.Length, dBLength);
        }

        void IDisposable.Dispose()
        {
            if (_webclient != null)
                _webclient.Dispose();
        }
    }
}
